{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "from vnpy.trader.app.ctaStrategy.ctaBacktesting import BacktestingEngine, OptimizationSetting, MINUTE_DB_NAME\n",
    "from vnpy.trader.app.ctaStrategy.strategy.strategyAtrRsi import AtrRsiStrategy\n",
    "#from vnpy.trader.app.ctaStrategy.strategy.strategyMultiTimeframe import MultiTimeframeStrategy\n",
    "from vnpy.trader.app.ctaStrategy.strategy.strategyMultiSignal import MultiSignalStrategy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 创建回测引擎对象\n",
    "engine = BacktestingEngine()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 设置回测使用的数据\n",
    "engine.setBacktestingMode(engine.BAR_MODE)    # 设置引擎的回测模式为K线\n",
    "engine.setDatabase(MINUTE_DB_NAME, 'IF0000')  # 设置使用的历史数据库\n",
    "engine.setStartDate('20130101')               # 设置回测用的数据起始日期"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 配置回测引擎参数\n",
    "engine.setSlippage(0.2)     # 设置滑点为股指1跳\n",
    "engine.setRate(0.3/10000)   # 设置手续费万0.3\n",
    "engine.setSize(300)         # 设置股指合约大小 \n",
    "engine.setPriceTick(0.2)    # 设置股指最小价格变动   \n",
    "engine.setCapital(1000000)  # 设置回测本金"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 在引擎中创建策略对象\n",
    "d = {'atrLength': 11}                     # 策略参数配置\n",
    "engine.initStrategy(AtrRsiStrategy, d)    # 创建策略对象\n",
    "#ngine.initStrategy(MultiTimeframeStrategy, d)    \n",
    "#engine.initStrategy(MultiSignalStrategy, {})    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 运行回测\n",
    "engine.runBacktesting()          # 运行回测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "# 显示逐日回测结果\n",
    "engine.showDailyResult()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 显示逐笔回测结果\n",
    "engine.showBacktestingResult()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 显示前10条成交记录\n",
    "for i in range(10):\n",
    "    d = engine.tradeDict[str(i+1)].__dict__\n",
    "    print 'TradeID: %s, Time: %s, Direction: %s, Price: %s, Volume: %s' %(d['tradeID'], d['dt'], d['direction'], d['price'], d['volume'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2018-02-16 22:15:18.251000\t------------------------------\n",
      "2018-02-16 22:15:18.251000\tsetting: {'atrLength': 12}\n",
      "2018-02-16 22:15:18.256000\t开始载入数据\n",
      "2018-02-16 22:15:18.319000\t载入完成，数据量：91381\n",
      "2018-02-16 22:15:18.319000\t开始回测\n",
      "2018-02-16 22:15:18.361000\t策略初始化完成\n",
      "2018-02-16 22:15:18.361000\t策略启动完成\n",
      "2018-02-16 22:15:18.361000\t开始回放数据\n",
      "2018-02-16 22:15:25.992000\t数据回放结束\n",
      "2018-02-16 22:15:25.992000\t计算按日统计结果\n",
      "2018-02-16 22:15:26.085000\t------------------------------\n",
      "2018-02-16 22:15:26.085000\tsetting: {'atrLength': 14}\n",
      "2018-02-16 22:15:26.087000\t开始载入数据\n",
      "2018-02-16 22:15:26.142000\t载入完成，数据量：91381\n",
      "2018-02-16 22:15:26.142000\t开始回测\n",
      "2018-02-16 22:15:26.183000\t策略初始化完成\n",
      "2018-02-16 22:15:26.183000\t策略启动完成\n",
      "2018-02-16 22:15:26.183000\t开始回放数据\n",
      "2018-02-16 22:15:34.799000\t数据回放结束\n",
      "2018-02-16 22:15:34.799000\t计算按日统计结果\n",
      "2018-02-16 22:15:34.881000\t------------------------------\n",
      "2018-02-16 22:15:34.881000\tsetting: {'atrLength': 16}\n",
      "2018-02-16 22:15:34.883000\t开始载入数据\n",
      "2018-02-16 22:15:34.935000\t载入完成，数据量：91381\n",
      "2018-02-16 22:15:34.935000\t开始回测\n",
      "2018-02-16 22:15:34.981000\t策略初始化完成\n",
      "2018-02-16 22:15:34.981000\t策略启动完成\n",
      "2018-02-16 22:15:34.981000\t开始回放数据\n",
      "2018-02-16 22:15:43.120000\t数据回放结束\n",
      "2018-02-16 22:15:43.120000\t计算按日统计结果\n",
      "2018-02-16 22:15:43.151000\t------------------------------\n",
      "2018-02-16 22:15:43.151000\t优化结果：\n",
      "2018-02-16 22:15:43.151000\t参数：[\"{'atrLength': 16}\"]，目标：819765.66\n",
      "2018-02-16 22:15:43.151000\t参数：[\"{'atrLength': 14}\"]，目标：534310.005\n",
      "2018-02-16 22:15:43.151000\t参数：[\"{'atrLength': 12}\"]，目标：278612.3988\n",
      "耗时：24.9000000954\n"
     ]
    }
   ],
   "source": [
    "# 优化配置\n",
    "setting = OptimizationSetting()                 # 新建一个优化任务设置对象\n",
    "setting.setOptimizeTarget('totalNetPnl')        # 设置优化排序的目标是策略净盈利\n",
    "setting.addParameter('atrLength', 12, 16, 2)    # 增加第一个优化参数atrLength，起始12，结束20，步进2\n",
    "#setting.addParameter('atrMa', 20, 30, 5)        # 增加第二个优化参数atrMa，起始20，结束30，步进5\n",
    "#setting.addParameter('rsiLength', 5)            # 增加一个固定数值的参数\n",
    "\n",
    "# 执行多进程优化\n",
    "import time\n",
    "start = time.time()\n",
    "#resultList = engine.runParallelOptimization(AtrRsiStrategy, setting)\n",
    "resultList = engine.runOptimization(AtrRsiStrategy, setting)\n",
    "print u'耗时：%s' %(time.time()-start)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 显示优化的所有统计数据\n",
    "for result in resultList:\n",
    "    print '-' * 30\n",
    "    print u'参数：%s，目标：%s' %(result[0], result[1])\n",
    "    print u'统计数据：'\n",
    "    for k, v in result[2].items():\n",
    "        print u'%s：%s' %(k, v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
